<?php

namespace common\behavior\CommonMessagePushing;


use common\model\EntityModel;
use common\model\UserModel;
use common\service\BehaviorService;
use common\service\ReviewRequestMessageService;
use common\service\TaskAssembleService;
use common\service\TaskService;
use common\service\UserService;
use Webman\Stomp\Client;

/**
 * 任务上游完成 消息通知
 */
class TaskUpstreanDoneBehavior
{
    /**
     * @param $params
     * @return void
     */
    public function run($params)
    {
        /***********  预处理开始  ************/
        $params = BehaviorService::getInstance()->dealParam(
            $params,
            [
                'task' => '',
                'entity' => '',
                'check_result' => '',
                'current_task_name' => 'strval',
                'relate_type' => 'strval',
                'template_id' => 'intval',
            ],
            [
                'task' => [],
                'entity' => [],
                'check_result' => [],
                'current_task_name' => '',
                'relate_type' => '',
                'template_id' => 0,
            ],
            'data',
            ['type' => 'task_upstream_done'],
        );
        /***********  行为判断  ************/
        if ($params === false) {
            return;
        }
        /***********  变量迁移  ************/
        list($task, $entity, $checkResult, $currentTaskName, $relateType, $templateId) = $params;
        if (empty($task) || empty($entity) || empty($checkResult) || empty($relateType) || empty($templateId)) {
            return;
        }
        /***********  预处理结束  ************/

        /***********  原逻辑迁移  ************/
        $notifyUserIdList = [];
        if ($task['assignee_producer'] > 0) {
            $notifyUserIdList[$task['assignee_producer']] = $task['assignee_producer'];
        }
        if ($task['executor'] > 0) {
            $notifyUserIdList[$task['executor']] = $task['executor'];
        }
        $saasUserList = [];
        if ($task['department_id'] > 0) {
            $param = [
                'param' => [
                    'filter' => [
                        'tenant_id' => $task['tenant_id'],
                        'department_id' => $task['department_id'],
                        'role_code' => TaskService::HEADMAN_CODE,
                    ],
                ],
            ];
            $departmentHeadmanList = teamones_request('teamones-im', 'tenant/select_department_user_department_info_merged', $param);
            $departmentHeadmanList = $departmentHeadmanList['data'];
            $unionIdList = array_column($departmentHeadmanList, 'user_id', 'user_id');
            if (!empty($unionIdList)) {
                $saasUserList = model(UserModel::class)->where(['union_id' => ['IN', array_values($unionIdList)]])->select();
                $saasUserList = array_column($saasUserList, null, 'union_id');
            }
        }
        if (!empty($notifyUserIdList)) {
            $tempSaasUserList = model(UserModel::class)->where(['id' => ['IN', implode(',', $notifyUserIdList)]])->select();
            $saasUserList = array_merge($saasUserList, array_column($tempSaasUserList, null, 'id'));
        }
        if (empty($saasUserList)) {
            return;
        }
        $taskName = TaskAssembleService::getInstance()->getNotifyTaskName($entity, $task);
        $first = '任务';
        if ($checkResult['flag'] === true) {
            $first .= $taskName . '的上游/关联全部完成';
        } else {
            $first .= $taskName . '的' . $relateType . $currentTaskName . '完成了';
        }
        $notifyParam = [
            'first' => '上游任务完成',
            'note_text' => $first,
            'remark' => "请及时查看",
            'tenant_id' => $task['tenant_id'],
            'project_id' => $task['project_id'],
            'task_id' => $task['id'],
            'module_code' => in_array(module_by_id($task['entity_module_id'])['code'], ['design', 'level', 'asset']) ? 'asset' : 'shot',
            'message_key' => 'task_upstream_done',
        ];
        $messageGenerated = [];
        foreach ($saasUserList as $saasUserItem) {
            $messageGenerated[] = [
                "param" => $notifyParam,
                'receiver' => $saasUserItem['union_id'],
                'template_id' => $templateId,
                'content_type' => 'card_message',
                'notice_type' => 'message_task',
                'is_popup' => 1,
                'message_key' => $notifyParam['message_key'],
                'project_id' => $task['project_id'],
            ];

        }
        /***********  发送新的队列  ************/
        foreach ($messageGenerated as $message) {
            Client::send('common_message_pushing', build_queue_data_with_xu([
                'message_generated' => [$message],
            ]));
        }
        /***********  结束  ************/
    }
}
